import traceback
import middleware
import url
import myhttp as http


def handle(client, request):
    assert isinstance(request, http.HttpRequest)
    # use middlewares to process request.
    for mw in middleware.middlewares:
        assert isinstance(mw, middleware.MiddleWare)
        response = mw.process_request(request)
        if response is not None:
            return response
    try:
        view, args = url.get_view_by_path(request.path)
        if request.method == "GET":
            response = view.get(request, **args)
        elif request.method == "POST":
            response = view.post(request, **args)
        else:
            raise http.unsupported_method
    except http.page_not_found:
        response = http.HttpResponseNotFound
    except http.unsupported_method:
        response = http.HttpResponseServerError
    except NotImplementedError:
        response = http.HttpResponseMethodNotAllowed
    except Exception:
        traceback.print_exc()
        response = http.HttpResponseServerError
    # use middlewares to process response.
    for mw in middleware.middlewares:
        mw.process_response(response)

    return response
